<?php

namespace Yjius\openapi\toutiao;

use Yjius\common\CurlHelper;

/**
 * 头条扫码登录
 * Class TouTiaoOauth
 * @package Yjius\openapi\toutiao
 * @date  2022/7/26 17:04
 */
class TouTiaoOauth
{
    //应用参数
    private $client_key = null;
    private $client_secret = null;
    private $redirect_uri = null;

    //最外层初始化时，YII_ENV 可以选择不同的应用
    public function __construct($config = [])
    {
        //裁入配置
        $this->client_key = $config['client_key'] ?: '';
        $this->client_secret = $config['client_secret'] ?: '';
        $this->redirect_uri = $config['redirect_uri'] ?: '';
        if (empty($this->client_key) || empty($this->client_secret) || empty($this->redirect_uri)) {
            throw new \Exception("载入配置错误，请检查参数是否正确");
        }
    }

    /**
     * 返回【第一步：请求CODE】的url
     */
    public function getCodeUrl($state = '')
    {
        $url = 'https://open.snssdk.com/auth/authorize/?';
        $url .= 'response_type=code';
        $url .= '&auth_only=1';
        $url .= '&client_key=' . $this->client_key;
        $url .= '&redirect_uri=' . urlencode($this->redirect_uri);
        $url .= '&state=' . $state;
        return $url;
    }

    /**
     * 第二步：通过code获取access_token
     * @param $code
     * @return bool|mixed|string
     */
    public function getAccessToken($code)
    {
        $params = [
            'code' => $code,
            'grant_type' => 'authorize_code',
            'client_key' => $this->client_key,
            'client_secret' => $this->client_secret,
        ];
        $url = 'https://open.snssdk.com/auth/token/';
        $res = CurlHelper::httpRequest($url, [], 'GET', $params);
        return json_decode($res, true);
    }

    /**
     * 第三步：获取用户信息
     * @param string $token
     * @param string $media_id
     * @return array
     */
    public function getLoginInfo($token, $media_id, $media_name)
    {
        $url = 'https://open.snssdk.com/data/user_profile/';
        $res = CurlHelper::httpRequest($url, [], 'GET', array(
            'client_key' => $this->client_key,
            'access_token' => $token,
            'open_id' => $media_id,
            'media_name' => $media_name,
        ));
        return json_decode($res, true);
    }

    /**
     * Purpose: 发图文
     * Author:yingjiusheng@gsdata.cn
     * @date 2022/7/26 17:09
     */
    public function postArticle($token, $params)
    {
        $url = 'https://mp.toutiao.com/open/new_article_post/';
        $params['access_token'] = $token;
        $params['client_key'] = $this->client_key;
        $res = CurlHelper::httpRequest($url, [], 'POST', $params);
        return json_decode($res, true);
    }

}